import { Component,ChangeDetectorRef } from '@angular/core';
import { NavController, NavParams,LoadingController,AlertController } from 'ionic-angular';

import { BaseService } from '../../app/core/data/BaseService';
import { DataService } from '../../app/core/data/DataService';

import { SignPage } from '../sign/sign';
import { SignNewPage } from '../sign_new/sign_new';
import { LeaveNewPage } from '../leave-new/leave-new';
import { VehiclePage } from '../vehicle/vehicle';
import { VehicleannalPage } from '../vehicleannal/vehicleannal';
import { TripPage } from '../trip/trip';
import { FormObject } from '../../app/form/FormObject';
import { CalendarPage } from '../calendar/calendar';
import { LeavePage } from '../leave/leave';
import { ApprovalPage } from '../approval/approval';
import { LoginPage } from '../../pages/login/login';
import { SecurityService } from '../../app/core/security/SecurityService';
import { SwglNewPage } from '../swgl_new/swgl_new';
import { FwglPage } from '../fwgl/fwgl';
import { SignHttp } from '../../app/buiness/SignHttp';

import { SignTextPage } from './form/sign_text';

declare var AMap;
/**
 * Generated class for the JobsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-jobs',
  templateUrl: 'jobs.html',
})
export class JobsPage {

  public user={};
  public mi={};
  public si={};
  //declare let AMap;

  public latitude: any = "";//维度
  public longitude: any = "";//经度
  public formattedAddress: string = "";
  public accuracy:string="";
  public swglnums:any = "";



  /**
   * 调用高德的接口，获取高精度的地图位置服务
   */
  goLocation() {
    let that = this;    
    let mapObj = new AMap.Map('iCenter');
    mapObj.plugin('AMap.Geolocation', function () {
        let geolocation = new AMap.Geolocation({        
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
        maximumAge: 0,           //定位结果缓存0毫秒，默认：0
        convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
        showButton: true,        //显示定位按钮，默认：true
        buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
        showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
        panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
        zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      });
      mapObj.addControl(geolocation);
      geolocation.getCurrentPosition();
      AMap.event.addListener(geolocation, 'complete', that.onComplete.bind(that));//返回定位信息
      AMap.event.addListener(geolocation, 'error', (data)=>{ 
        that.qdLoading.dismiss();
        console.log('定位失败' + data['message']);
        let temp= that.alertCtrl.create({
          title: '系统提示',
          subTitle: "定位失败，"+data['message'],
          buttons: ['确定']
        });
        temp.present();
      });      //返回定位出错信息
    });
  }  //解析定位结果
  onComplete(data) {
   /* console.log(data);    
    console.log(data.position.toString());    
    console.log(data.formattedAddress);    
    var str=['定位成功'];
    str.push('经度：' + data.position.getLng());
    str.push('纬度：' + data.position.getLat());    
    if(data.accuracy){
      str.push('精度：' + data.accuracy + ' 米');
    }//如为IP精确定位结果则没有精度信息
    str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));   
    let alert = this.alertCtrl.create({
      title: '系统提示',
      subTitle: "高德导航到坐标位置x:"+data.position.getLng()+",y:"+data.position.getLat(),
      buttons: ['确定']
    });
    alert.present();*/
    this.longitude=data.position.getLng();
    this.latitude=data.position.getLat();  
    this.accuracy=data.accuracy;
    this.analysisPositionFun(this.longitude,this.latitude);
     // document.getElementById('tip').innerHTML = str.join('<br>');
  }


  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private baseService:BaseService,
    private dataService:DataService,
    private alertCtrl: AlertController,
    private securityService:SecurityService,
    public changeDetectorRef:ChangeDetectorRef,
    private signHttp:SignHttp,
    public loadingCtrl: LoadingController) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad JobsPage');
  }
  toSignNewPage() {
    this.navCtrl.push(SignNewPage);
  }
  toLeaveNewPage() {
    this.navCtrl.push(LeaveNewPage);
  }
  startNewBpm(bpmkey:string,formname:string){
    let para={};
    para["bk"]=bpmkey;
    para["fn"]=formname;
    para["vi"]=formname;
    let formObject:FormObject=new FormObject(this.dataService,this.baseService,this.changeDetectorRef,this.loadingCtrl);
    para["dk"]=formObject.getGUID();
    para["FIELD_ISNEW"]=true;
    if(formname=="gzqjgl"){//请假
      this.navCtrl.push(LeavePage,para);
    }else if(formname=="gzccgl"){//出差
      this.navCtrl.push(CalendarPage,para);
    }else if(formname=="gzpublishfile"){//发文
      this.navCtrl.push(FwglPage,para);
    }else if(formname=="gzclsq"){//车辆使用申请
      this.navCtrl.push(VehiclePage,para);
    }
  }

  toApprovalPage(){
    this.navCtrl.push(ApprovalPage);
  };

  toSwglNewPage(){
    this.navCtrl.push(SwglNewPage);
  };

  //初始化页面
  ionViewDidEnter(){
    this.user={};
    if(this.securityService.user==null || this.securityService.user["userid"]==null){
      this.securityService.getUserInfo(()=>{
        this.user= this.securityService.user;
        this.mi=this.securityService.mi;
        this.si=this.securityService.si;
        this.dataService.getRowCounts("gzreceiveview",{"sfqr":"0"}).subscribe((data)=>{
          if(data>0){
            window.localStorage.setItem("swglnums",data+"")
            this.swglnums=window.localStorage.getItem("swglnums");
          }else if(data==0){
            window.localStorage.setItem("swglnums","");
            this.swglnums=window.localStorage.getItem("swglnums");
          }
        });
      },()=>{
        this.user = {};
        this.goLogin();
      })
    }else{
      this.user= this.securityService.user;
      this.mi=this.securityService.mi;
      this.si=this.securityService.si;
      this.dataService.getRowCounts("gzreceiveview",{"sfqr":"0"}).subscribe((data)=>{
        if(data>0){
          window.localStorage.setItem("swglnums",data+"")
          this.swglnums=window.localStorage.getItem("swglnums");
        }else if(data==0){
          window.localStorage.setItem("swglnums","");
          this.swglnums=window.localStorage.getItem("swglnums");
        }
      });
    }
  };

  //跳转到登录界面
  goLogin(){
    this.navCtrl.push(LoginPage);
  };

  goSign() {
    this.navCtrl.push(SignPage);
  }

  goVehicleAnnal() {
    this.navCtrl.push(VehicleannalPage);
  }

  goTrip() {
    this.navCtrl.push(TripPage);
  }

  goLeave() {
    this.navCtrl.push(LeaveNewPage);
  }

  public type:string="";
  public qdLoading:any="";
  /**
   * 用户签到同时定位服务
   */
  userQdAndPostion(type:string){
    this.qdLoading = this.loadingCtrl.create({
      content: '获取坐标中，请稍后...'//数据加载中显示
    });
    this.qdLoading.present();
    this.type=type;
    this.latitude="";
    this.longitude="";
    this.accuracy="";
    this.formattedAddress="";
    this.goLocation();
  };

  userQd(){
    this.qdLoading.dismiss();
    let text:string="";
    if(this.type=="signin"){
      text="确定签到？";
    }else{
      text="确定签退？";
    }
    let confirm =this.alertCtrl.create({
      title: '系统提示?',
      message: "当前位置"+this.formattedAddress+","+text,
      buttons: [
        {
          text: '确定',
          handler: () => {
           // console.log('Disagree clicked');
           this.gzqdgldata("create",this.type);
          }
        },
        {
          text: '取消',
          handler: () => {
            //console.log('Agree clicked');
          }
        }
      ]
    });
    confirm.present();
  }

  gzqdgldata(method:string,type:string){
    this.qdLoading = this.loadingCtrl.create({
      content: '打卡中，请稍后...'//数据加载中显示
    });
    this.qdLoading.present();
    this.signHttp.gzqdgldata(method,type,this.latitude,this.longitude,this.formattedAddress,this.accuracy).subscribe(data => {
      this.qdLoading.dismiss();
      if(data){
        if(data["status"]){
          if(data["type"]=="create"){
            let alert = this.alertCtrl.create({
              title: '系统提示',
              subTitle: data["message"],
              buttons: ['确定']
            });
            alert.present();
          }else if(data["type"]=="update"){
            let confirm =this.alertCtrl.create({
              title: '系统提示?',
              message: data["message"],
              buttons: [
                {
                  text: '确定',
                  handler: () => {
                   // console.log('Disagree clicked');
                   this.gzqdgldata("update",type);
                  }
                },
                {
                  text: '取消',
                  handler: () => {
                    //console.log('Agree clicked');
                  }
                }
              ]
            });
            confirm.present();
          }else if(data["type"]=="opentext"){
            let confirm =this.alertCtrl.create({
              title: '系统提示?',
              message: data["message"],
              buttons: [
                {
                  text: '确定',
                  handler: () => {
                    this.navCtrl.push(SignTextPage,data["data"]);
                  }
                },
                { text: '取消', handler: () => {}},
              ]
            });
            confirm.present();
          }
        }else{
          let alert = this.alertCtrl.create({
            title: '系统提示',
            subTitle: data["message"],
            buttons: ['确定']
          });
          alert.present();
        }
      }else{
        let alert = this.alertCtrl.create({
          title: '系统提示',
          subTitle: '打卡失败，请重试！',
          buttons: ['确定']
        });
        alert.present();
      }
    }, err => {
      let alert = this.alertCtrl.create({
        title: '系统提示',
        subTitle: '打卡失败，请重试！',
        buttons: ['确定']
      });
      alert.present();
    });
  }

  // openText(data?: any){
  //   let modal = this.modalCtrl.create(SignTextPage,data);
  //   modal.present();
  // }

  // 获取经纬度，转换地址。(原始方式，定位精度不高)
getPositionFun() {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      console.log(position);
      console.log('纬度: ' + position.coords.latitude + '\n' +
        '经度: ' + position.coords.longitude + '\n' +
        '海拔: ' + position.coords.altitude + '\n' +
        '水平精度: ' + position.coords.accuracy + '\n' +
        '垂直精度: ' + position.coords.altitudeAccuracy + '\n' +
        '方向: ' + position.coords.heading + '\n' +
        '速度: ' + position.coords.speed + '\n' +
        '时间戳: ' + position.timestamp + '\n');
     // console.log(AMap);
      // 外面定义获取经纬度的变量，方便界面显示。
      this.latitude = position.coords.latitude;
      this.longitude = position.coords.longitude;

      let alert = this.alertCtrl.create({
        title: '系统提示',
        subTitle: "导航到坐标位置x:"+this.longitude+",y:"+this.latitude,
        buttons: ['确定']
      });
      alert.present();

     
    }, this.onError, { timeout: 30000 });
}



//定位数据获取失败响应
onError(error) {
  alert('code: ' + error.code + '\n' +
    'message: ' + error.message + '\n');
}

testAnalysis(){
 // this.analysisPositionFun();
 this.analysisPositionFun(113.018258,28.095051);
};

/**
 * 通过经纬度解析当前的位置
 * @param longitude 
 * @param latitude 
 */
analysisPositionFun(longitude:any,latitude:any){
  AMap.service("AMap.Geocoder", () => {
    let geocoder = new AMap.Geocoder({
      //city: "010",
      radius: 100 //范围，默认：500
    });
    console.log(geocoder, "fuwu");
    let positionInfo = [longitude + "", latitude + ""];
    console.log(positionInfo);
    geocoder.getAddress(positionInfo, (status, result) => {
      console.log(status, result, "转换定位信息");
      if (status === 'complete' && result.info === 'OK') {
        //获得了有效的地址信息:
        console.log(result.regeocode.formattedAddress);
        this.formattedAddress = result.regeocode.formattedAddress;
        /*let alert = this.alertCtrl.create({
          title: '系统提示',
          subTitle: this.formattedAddress.toString(),
          buttons: ['确定']
        });
        alert.present();*/

        this.userQd();
      } else {
        this.qdLoading.dismiss();
      
           //获取地址失败
        let alert = this.alertCtrl.create({
          title: '系统提示',
          subTitle: "定位失败",
          buttons: ['确定']
        });
        alert.present();
      
       
      }
    })
  });
}
  

}
